package v8s

import (
	"fmt"
	"net/http"

	"v8s-api/rest-api/target/generated-sources"
	"v8s-sm-proxy/internal/configuration"
)

type (
	Client struct {
		*generated.ClientWithResponses
	}
)

func NewClient(properties configuration.V8SProperties) *Client {
	oapi, err := generated.NewClientWithResponses(
		properties.Http.BaseUrl,
		withHttpClient(properties.Http),
	)
	if err != nil {
		panic(err)
	}

	return &Client{ClientWithResponses: oapi}
}

func withHttpClient(properties configuration.HttpClientProperties) func(client *generated.Client) error {
	return func(client *generated.Client) error {
		impl := &http.Client{}
		client.Client = impl

		impl.Timeout = properties.RequestTimeout

		config, err := properties.TLS.ToConfig()
		if err != nil {
			return fmt.Errorf("cannot load server certificates pair: %w", err)
		}

		if config != nil {
			transport := http.DefaultTransport.(*http.Transport).Clone()
			transport.TLSClientConfig = config
			impl.Transport = transport
		}

		return nil
	}
}
